﻿#include "TouchHandler.h"

#include <QDebug>
#include <QVector>

QTouchPointState _touchTranslate(uint8_t src)
{
    if (src == TlvTouchDef::FINGER_PERSS) {
        return QTouchPointState::TouchPointPressed;
    } else if (src == TlvTouchDef::FINGER_RELEASE) {
        return QTouchPointState::TouchPointReleased;
    } else if (src == TlvTouchDef::FINGER_NULL) {
        return QTouchPointState::TouchPointReleased;
    }
    return QTouchPointState::TouchPointMoved;
}

TouchHandler::TouchHandler(QObject *parent)
    : QObject{parent}
{
    connect(TlvThreadCom::instance(), &TlvThreadCom::dataReceived, this, &TouchHandler::handleTlvData);
}

void TouchHandler::handleTlvData(const Tlv& tlv)
{
    static QList<TouchPoint> lastPoints;
    if (tlv.tag() != TlvTag::Tlv_TOUCH_EVENT) return;
    QByteArray touchData = tlv.value();

    if (touchData.length() != 50) return;

    QList<TouchPoint> points;
    for (uint8_t i = 0; i < 10; i++) {
        uint8_t idx = i * 5;
        uint8_t id_e = getByteFromBytes(touchData, idx + 0);

        uint16_t x = getUi16FromBytesBE(touchData, idx + 1);
        uint16_t y = getUi16FromBytesBE(touchData, idx + 3);

        uint8_t pid = (id_e >> 4);  // 手指id
        uint8_t e = id_e & 0x0F;
        QTouchPointState ps = _touchTranslate(e);
        bool valid = (e != TlvTouchDef::FINGER_NULL);

        TouchPoint p(x, y, ps, pid, valid);
        points.push_back(p);
    }
    if (!lastPoints.isEmpty()) {
        for (uint8_t i = 0; i < 10; i++) {
            if (!points[i].isValid() && lastPoints[i].isValid() && lastPoints[i].state() == QTouchPointState::TouchPointMoved) {
                points[i].setPos(lastPoints[i].pos());
                points[i].setValid(true);
                points[i].setState(QTouchPointState::TouchPointReleased);
            }
            // if (!points[i].isValid()) continue;
            // QTouchPointState lastState = lastPoints[i].state();
            // if ((lastState == QTouchPointState::TouchPointPressed ||
            //      lastState == QTouchPointState::TouchPointStationary) &&
            //     points[i].state() == QTouchPointState::TouchPointPressed) {
            //     points[i].setState(QTouchPointState::TouchPointStationary);
            // }
        }
    }

    // TouchPoint p = points[0];
    // qDebug() << p.id() << p.pos() << p.state() << p.isValid();

    lastPoints = points;
    emit touched(points);
}
